package net.esj.basic.utils.i18n;

import java.util.Locale;

import javax.servlet.http.HttpSession;

import net.esj.basic.core.view.filter.I18NFilter;
import net.esj.basic.utils.ApplicationBeanContext;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.MessageSource;

import com.opensymphony.xwork2.ActionContext;

public class LocaleUtils {
	
	public static final Locale locale_zh_CN = new Locale("zh", "CN"); 
	
	public static final Locale locale_en_US= new Locale("en", "US"); 
	
	public static final Locale getLocale(String key){
		String[] d = key.split("_");
		if(d.length>1){
			return new Locale(d[0],d[1]);
		}else{
			return new Locale(d[0]);
		}
	}
	
	public static final Locale findLocale(){ 
		HttpSession session = ServletActionContext.getRequest().getSession();
		if(session!=null){
			Locale locale = (Locale) session.getAttribute(I18NFilter.STRUTS_I18N_KEY);
			if(locale!=null){
				return locale;
			}
		}
		ActionContext ctx = ActionContext.getContext();
        if (ctx != null) {
            return ctx.getLocale();
        }
		return Locale.getDefault();
	}
	
	public static MessageSource getMessageSource(){
		return (MessageSource) ApplicationBeanContext.getBean("messageSource");
	}
	
	public static String getMessage(String key,Object...objects ){
		return getMessageSource().getMessage(key, objects, locale_zh_CN);
	}
	
	public static String getMessage(String key,Locale locale, Object...objects){
		return getMessageSource().getMessage(key, objects, locale);
	}
	
	
}
